package com.atguigu.gmall.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@CanalEventListener         // 声明该类是一个Canal的事件监听器
@Slf4j
public class ProductBinLogListener {

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    /**
     *  @UpdateListenPoint: 监听update操作
     *  @InsertListenPoint: 监听insert操作
     *  @DeleteListenPoint: 监听delete操作
     *
     *  @ListenPoint：监听所有的写操作
     */
    @ListenPoint(destination = "example" , schema = "gmall_product" , table = "sku_info")
    public void productUpdateMethod(CanalEntry.RowData rowData) {

        // 获取修改之前数据
//        List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
//        beforeColumnsList.forEach(column -> {
//            String name = column.getName();
//            String value = column.getValue();
//            log.info("name: {} , value: {}" , name , value);
//        });
//
//        System.out.println("------------------------------------------------------------------------------------------");

        // 获取修改之后的数据
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        afterColumnsList.forEach(column -> {
            String name = column.getName();
            String value = column.getValue();
            if("id".equals(name)) {
                redisTemplate.delete("sku:info:" + value) ;
                log.info("从redis中删除了skuId: {}的数据" , value);
            }
        });

    }

}
